//构造方法
function Window(windowID, width, height, titleName,options) {
    //窗体数据
    this.windowID = $(".window").length;
    this.titleName = titleName;
    this.originalHeight = height;
    this.originalWidth = width;
    /*居中显示*/
    this.originalLeft = parseInt((document.body.clientWidth - width+this.windowID*10) / 2);
    this.originalTop = parseInt((document.body.clientHeight - height+this.windowID*10) / 2);
    this.bIsMax = this.bIsMin = this.bIsCloed = this.bIsDraging = this.bIsChanging = false;
    this.defaults = {
         closeCallback:function () {
         }
    },
        this.$options = $.extend({}, this.defaults, options)


}


Window.prototype = {
    initialize: function () {
        /*------------原型方法：初始化---------------------------*/
        //原型方法：创建HTML内容
        this.createWindow();
        this.showWindow();
        this.previousHeight;
        this.previousWidth;
        this.previousLeft;
        this.previousTop;

        //激活窗口的各个方法
        this.drag(this);
        this.changeSize(this);
        this.respondToButton(this);
        this.changeStyle(this);
    },
    createWindow: function () {
        /*------------原型方法：创建HTML内容 & 获得窗口各部件的对象---------------*/
        var window = this.create_dom("div");
        var head = this.create_dom("div");
        var title = this.create_dom("div");
        var button = this.create_dom("div");
        var minimize = this.create_dom("div");
        var maximize = this.create_dom("div");
        var close = this.create_dom("div");
        var content = this.create_dom("div");
        var windowN = this.create_dom("div");
        var windowE = this.create_dom("div");
        var windowS = this.create_dom("div");
        var windowW = this.create_dom("div");
        var windowNE = this.create_dom("div");
        var windowES = this.create_dom("div");
        var windowSW = this.create_dom("div");
        var windowWN = this.create_dom("div");
        var windowTag = this.create_dom("div");

        window.id = "window_" + this.windowID;
        head.id = "window_head_" + this.windowID;
        title.id = "window_head_title_" + this.windowID;
        button.id = "window_head_btn_" + this.windowID;
        minimize.id = "window_head_btn_minimize_" + this.windowID;
        maximize.id = "window_head_btn_maximize_" + this.windowID;
        close.id = "window_head_btn_close_" + this.windowID;
        content.id = "window_content_" + this.windowID;
        windowTag.id = "window_tag_" + this.windowID;

        window.className = "window";
        head.className = "windowHeader";
        title.className = "windowHeaderTitle";
        button.className = "windowButton";
        minimize.className = "windowMinimize fa fa-window-minimize ";
        maximize.className = "windowMaximize fa fa-window-maximize";
        close.className = "windowClose fa fa-window-close";
        content.className = "windowContent";
        windowN.className = "windowN windowSide";
        windowE.className = "windowE windowSide";
        windowS.className = "windowS windowSide";
        windowW.className = "windowW windowSide";
        windowNE.className = "windowNE windowSide";
        windowES.className = "windowES windowSide";
        windowSW.className = "windowSW windowSide";
        windowWN.className = "windowWN windowSide";
        windowTag.className = "windowTag";

        document.body.appendChild(window);
        window.appendChild(head);
        window.appendChild(content);
        window.appendChild(windowN);
        window.appendChild(windowE);
        window.appendChild(windowS);
        window.appendChild(windowW);
        window.appendChild(windowNE);
        window.appendChild(windowES);
        window.appendChild(windowSW);
        window.appendChild(windowWN);
        head.appendChild(button);
        head.appendChild(title);
        button.appendChild(minimize);
        button.appendChild(maximize);
        button.appendChild(close);
        this.windowQuery("windowsList").appendChild(windowTag);
        //所有对象共用一个windowPreview(用来改变大小时的预览)
        if (!this.windowQuery("windowPreview")) {
            var windowPreview = this.create_dom("div");
            windowPreview.id = "windowPreview";
            document.body.appendChild(windowPreview);
        }

        //获得窗口各部件的对象
        this.windowObj = window;
        this.headerObj = head;
        this.title = title;
        this.windowContent = content;
        this.windowTag = windowTag;
        this.windowBtnMin = minimize;
        this.windowBtnMax = maximize;
        this.windowBtnClose = close;
        //获得窗口的四边四角的对象数组
        this.windowSideArray = this.myGetElementsByClassName(false, "windowSide", "div", "window_" + this.windowID);
    },
    showWindow: function () {
        var _this = this;
        /*------------原型方法：显示新建好的窗口-------------------*/
        //初始化窗体坐标、高宽
        this.windowObj.style.left = this.originalLeft + "px";
        this.windowObj.style.top = this.originalTop + "px";
        this.windowObj.style.width = this.originalWidth + "px";
        this.windowObj.style.height = this.originalHeight + "px";
        //建第一个窗口时,this.getMaxZIndex() 为NaN,所以须判断
        //必须从100开始，原因未名，如果从100以下开始，z-index到了100就不会再往上增（？？？）
        this.floatUp();
        //添加文字内容
        this.windowTag.innerText = this.windowTag.innerHTML = this.titleName;
        this.title.innerText = this.title.innerHTML = this.titleName;
    },
    drag: function (objItself) {
        /*------------原型方法：窗体拖放函数----------------------*/
        var _this = this;
        //改变被选中窗口的z-index
        objItself.windowObj.onmousedown = function () {
            _this.floatUp();
            /*return false;*/
        }
        //鼠标按下之后一系列动作
        objItself.headerObj.onmousedown = function (event) {
            objItself.bIsDraging = true;
            var event = event || window.event;
            if (event.button == 2) return false;
            //改变鼠标样式
            document.body.style.cursor = "move";
            //鼠标离窗口左、上边界的距离
            disX = event.clientX - objItself.windowObj.offsetLeft;
            disY = event.clientY - objItself.windowObj.offsetTop;
            //窗口随鼠标移动
            document.onmousemove = function (event) {
                if (!objItself.bIsDraging) return false;
                var event = event || window.event;
                //对窗口可移动范围进行限制
                var newLeft = event.clientX - disX;
                var newTop = event.clientY - disY;

                if (newLeft < 0)
                    newLeft = 0;
                if (newLeft > document.body.clientWidth - objItself.windowObj.offsetWidth)
                    newLeft = document.body.clientWidth - objItself.windowObj.offsetWidth;

                if (newTop < objItself.windowTag.offsetHeight)
                    newTop = objItself.windowTag.offsetHeight;
                if (newTop > document.body.clientHeight - objItself.windowObj.offsetHeight)
                    newTop = document.body.clientHeight - objItself.windowObj.offsetHeight;

                objItself.windowObj.style.left = newLeft + "px";
                objItself.windowObj.style.top = newTop + "px";
            }
            //鼠标放开，停止拖放
            document.onmouseup = function () {
                objItself.bIsDraging = false;
                document.body.style.cursor = "";
            }
            /*return false;*/
        }
    },
    changeSize: function (objItself) {
        /*------------原型方法：八个方向改变窗体大小----------------*/
        var cursorStyle = ["n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "se-resize", "sw-resize", "nw-resize"];
        var windowPreview = this.windowQuery("windowPreview");

        for (var i = 0; i < this.windowSideArray.length; i++) {
            this.windowSideArray[i].index = i;
            //改变鼠标样式
            this.windowSideArray[i].onmouseover = function (event) {
                //最大化时不改变窗口
                if (objItself.bIsMax) return false;
                document.body.style.cursor = cursorStyle[this.index];
            }
            //还原鼠标样式
            this.windowSideArray[i].onmouseout = function () {
                if (!objItself.bIsChanging)
                    document.body.style.cursor = "";
            }
            //鼠标移动，改变大小
            this.windowSideArray[i].onmousedown = function (event) {
                //最大化状态时不改变窗体大小
                if (objItself.bIsMax) return false;
                //鼠标右键时不改变窗体大小
                var event = event || window.event;
                //if(event.button == 2) return false;

                objItself.bIsChanging = true;
                var index = this.index;

                var previousX, previousY, previousHeight, previousWidth, previousTop, previousLeft;
                //记录鼠标按下时的窗口高宽、坐标属性 和 鼠标所在坐标
                recordWindowState();
                //显示预览窗口并初始化大小
                initializePreviewWindow();
                //鼠标移动 改变预览窗口的大小
                document.onmousemove = changePreviewWindowSize;
                //鼠标上升，将预览窗口的属性赋予实体窗口
                document.onmouseup = changeWindowSize;

                //显示预览窗口并初始化大小
                function initializePreviewWindow() {
                    windowPreview.style.display = "block";
                    windowPreview.style.height = previousHeight + "px";
                    windowPreview.style.width = previousWidth + "px";
                    windowPreview.style.left = previousLeft + "px";
                    windowPreview.style.top = previousTop + "px";
                }

                //记录鼠标按下时的窗口高宽、坐标属性 和 鼠标所在坐标
                function recordWindowState() {
                    previousHeight = (objItself.windowObj.offsetHeight - objItself.windowObj.clientTop * 2);//不能忽略border-width
                    previousWidth = (objItself.windowObj.offsetWidth - objItself.windowObj.clientLeft * 2);
                    previousLeft = (objItself.windowObj.offsetLeft);
                    previousTop = (objItself.windowObj.offsetTop);
                    previousX = event.clientX;
                    previousY = event.clientY;
                }

                //鼠标移动 改变预览窗口的大小
                function changePreviewWindowSize(event) {
                    var event = event || window.event;
                    var bTop = bRight = bBottom = bLeft = false;
                    //八个方向，分别为N、E、S、W、NE、SW、SW、NW 利用bool来判断鼠标点击了哪个windowSide
                    switch (index) {
                        case 0:
                            bTop = true;
                            break;
                        case 1:
                            bRight = true;
                            break;
                        case 2:
                            bBottom = true;
                            break;
                        case 3:
                            bLeft = true;
                            break;
                        case 4:
                            bTop = bRight = true;
                            break;
                        case 5:
                            bRight = bBottom = true;
                            break;
                        case 6:
                            bBottom = bLeft = true;
                            break;
                        case 7:
                            bLeft = bTop = true;
                            break;
                        default:
                            break;
                    }
                    //向北改变高度
                    if (bTop) {
                        var newNorthHeigh = previousHeight - (event.clientY - previousY);
                        if (newNorthHeigh < objItself.originalHeight)
                            newNorthHeigh = objItself.originalHeight;
                        if (newNorthHeigh > previousTop + previousHeight - objItself.windowTag.offsetHeight)
                            newNorthHeigh = previousTop + previousHeight - objItself.windowTag.offsetHeight;

                        var newTop = previousTop + (event.clientY - previousY);
                        if (newTop > previousTop + previousHeight - objItself.originalHeight)
                            newTop = previousTop + previousHeight - objItself.originalHeight;
                        if (newTop < objItself.windowTag.offsetHeight)
                            newTop = objItself.windowTag.offsetHeight;

                        windowPreview.style.top = newTop + "px";
                        windowPreview.style.height = newNorthHeigh + "px";
                        bTop = false;
                    }

                    //向东改变宽度
                    if (bRight) {
                        var newEastWidth = previousWidth + (event.clientX - previousX);
                        if (newEastWidth < objItself.originalWidth)
                            newEastWidth = objItself.originalWidth;
                        if (newEastWidth > document.body.clientWidth - previousLeft - objItself.windowObj.clientLeft * 2)
                            newEastWidth = document.body.clientWidth - previousLeft - objItself.windowObj.clientLeft * 2;

                        windowPreview.style.width = newEastWidth + "px";
                        bRight = false;
                    }

                    //向南改变高度
                    if (bBottom) {
                        var newSouthHeight = previousHeight + (event.clientY - previousY);
                        if (newSouthHeight < objItself.originalHeight)
                            newSouthHeight = objItself.originalHeight;
                        if (newSouthHeight > document.body.clientHeight - previousTop - objItself.windowObj.clientTop * 2)
                            newSouthHeight = document.body.clientHeight - previousTop - objItself.windowObj.clientTop * 2;

                        windowPreview.style.height = newSouthHeight + "px";
                        bBottom = false;
                    }

                    //向西改变宽度
                    if (bLeft) {
                        var newWestWidth = previousWidth - (event.clientX - previousX);
                        if (newWestWidth < objItself.originalWidth)
                            newWestWidth = objItself.originalWidth;
                        if (newWestWidth > previousLeft + previousWidth)
                            newWestWidth = previousLeft + previousWidth;

                        var newLeft = previousLeft + (event.clientX - previousX);
                        if (newLeft > previousLeft + previousWidth - objItself.originalWidth)
                            newLeft = previousLeft + previousWidth - objItself.originalWidth;
                        if (newLeft < 0)
                            newLeft = 0;

                        windowPreview.style.left = newLeft + "px";
                        windowPreview.style.width = newWestWidth + "px";
                        bLeft = false;
                    }
                }

                //鼠标上升，将预览窗口的属性赋予实体窗口
                function changeWindowSize() {
                    if (!objItself.bIsChanging) return false;		//免得被还原最大化时所干扰
                    //将预览窗口高宽、坐标赋予实体窗口

                    objItself.windowObj.style.width = windowPreview.offsetWidth - objItself.windowObj.clientLeft * 2 + "px";
                    objItself.windowObj.style.height = windowPreview.offsetHeight - objItself.windowObj.clientTop * 2 + "px";
                    objItself.windowObj.style.left = windowPreview.offsetLeft + "px";
                    objItself.windowObj.style.top = windowPreview.offsetTop + "px";
                    document.body.style.cursor = "";
                    windowPreview.style.display = "";
                    objItself.bIsChanging = false;
                }
            }
        }
    },
    respondToButton: function (objItself) {
        var _this = this;
        /*----------------原型方法：最小最大关闭---------------------*/
        var previousHeight, previousWidth, previousTop, previousLeft;

        //防止事件冒泡
        this.windowBtnMin.onmousedown = this.windowBtnMax.onmousedown = this.windowBtnClose.onmousedown = function (event) {
            var event = event || window.event;
            //判断浏览器的类型，在基于ie内核的浏览器中的使用cancelBubble
            if (window.event) {
                event.cancelBubble = true;
            } else {
                event.preventDefault(); //在基于firefox内核的浏览器中支持做法stopPropagation
                event.stopPropagation();
            }
            var event = event || window.event;
        }
        //最小化
        this.windowBtnMin.onclick = function (event) {
            /*这一行可能是多余的*/
            var event = event || window.event;
            _this.minimize();
        }
        this.windowTag.onclick = function () {
            _this.tag_hover_window();
        }
        //最大化(最大化按钮和双击头部)
        this.headerObj.ondblclick = this.windowBtnMax.onclick = function () {
            _this.maximize$$recover();
        }
        //关闭
        this.windowBtnClose.onclick = function () {
            _this.closeWindow();
        }

    },
    tag_hover_window: function () {
        //恢复窗口
        if (this.bIsMin) {
            /*恢复从窗口并且在视窗最前面*/
            this.windowObj.style.display = "block";
            this.floatUp();
            this.bIsMin = false;
        }

        else if (this.windowTag.className === 'windowTag') {
            this.floatUp();
            this.bIsMin = false;
        } else { //最小化窗口

            $.Toast("亲你好", "您的程序将在后台运行！", "success", {
                has_icon: true,
                has_close_btn: true,
                fullscreen: false,
                timeout: 4000,
                sticky: false,
                has_progress: true,
                rtl: false,
            });
            this.windowTag.className = 'windowTag'
            this.windowObj.style.display = "none";
            this.bIsMin = true;
        }
    },
    maximize$$recover: function () {
        if (!this.bIsMax) {
            //改变被选中窗口的z-index
            this.floatUp();
            this.windowTag.className = "windowTagCurrent";
            previousHeight = this.windowObj.offsetHeight - this.windowObj.clientTop * 2;
            previousWidth = this.windowObj.offsetWidth - this.windowObj.clientLeft * 2;
            previousLeft = this.windowObj.offsetLeft;
            previousTop = this.windowObj.offsetTop;
            this.windowObj.style.height = document.body.clientHeight - this.windowTag.offsetHeight - this.windowObj.clientTop * 2 + "px";
            this.windowObj.style.width = document.body.clientWidth - this.windowObj.clientLeft * 2 + "px";
            this.windowObj.style.left = 0 + "px";
            this.windowObj.style.top = this.windowTag.offsetHeight + "px";
            this.bIsMax = true;
        } else {
            this.windowObj.style.height = previousHeight + "px";
            this.windowObj.style.width = previousWidth + "px";
            this.windowObj.style.left = previousLeft + "px";
            this.windowObj.style.top = previousTop + "px";
            this.bIsMax = false;
        }
    },
    minimize: function () {
        this.windowObj.style.display = "none";
        this.bIsMin = true;
        this.windowTag.className = "windowTag"

    },
    closeWindow: function () {
        /*先执行回调再清空window*/
        if(typeof this.$options.closeCallback == 'function'){
            this.$options.closeCallback();
        }
        document.body.removeChild(this.windowQuery("window_" + this.windowID));
        this.windowQuery("windowsList").removeChild(this.windowQuery("window_tag_" + this.windowID));

    },
    floatUp: function () {
        var max = this.getMaxZIndex() ? (this.getMaxZIndex() + 1) : 100;
        if (this.windowObj.style.zIndex != max) {
            if (document.getElementsByClassName('windowTagCurrent')[0]) {
                document.getElementsByClassName('windowTagCurrent')[0].className = 'windowTag';
            }
            this.windowObj.style.zIndex = max;
            this.windowTag.className = "windowTagCurrent";
        }
    },
    ajaxLoad: function (url) {

        var _windowContent = this.windowContent;
        jQuery.get(url, function (r) {
            jQuery(_windowContent).html(r);
        }, "html");
    }
   /* startApp: function (app) {

        app.init(this.windowContent);
    }*/,
    changeStyle: function (objItself) {
        var _this = this;
        this.windowBtnMin.onmouseover = this.windowBtnMax.onmouseover = this.windowBtnClose.onmouseover = function () {
            this.style.background = "#B5E0F2";
            this.style.height = "20px";
        }
        this.windowBtnMin.onmouseout = this.windowBtnMax.onmouseout = this.windowBtnClose.onmouseout = function () {
            this.style.background = "#CECECE";
            this.style.height = "15px";
        }
    },
    create_dom: function (tagName) {
        return document.createElement(tagName);
    },
    windowQuery: function (idOrTagName, parentID) {
        if (parentID == "body")
            return document.getElementsByTagName(idOrTagName);
        else if (parentID)
            return document.getElementById(parentID).getElementsByTagName(idOrTagName);
        else
            return document.getElementById(idOrTagName);
    },
    myGetElementsByClassName: function (bool, className, tagName, parentID) {
        var tagArray = this.windowQuery(tagName, parentID);
        var resultArray = new Array();
        for (var i = 0; i < tagArray.length; i++) {
            if (bool) {
                if (tagArray[i].className == className) {
                    resultArray.push(tagArray[i]);
                }
            } else {
                if (tagArray[i].className.indexOf(className) != -1) {
                    resultArray.push(tagArray[i]);
                }
            }
        }
        return resultArray;
    },
    getMaxZIndex: function () {
        var windowsArray = this.myGetElementsByClassName(true, "window", "div", "body");
        var maxZIndex = windowsArray[0].style.zIndex;
        for (var i = 1; i < windowsArray.length; i++) {
            if (maxZIndex < windowsArray[i].style.zIndex)
                maxZIndex = windowsArray[i].style.zIndex;
        }
        return parseInt(maxZIndex);
    }
}

